<template>
  <div class="myDialog">
    <!-- 弹窗组件 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="title"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      width="780px"
    >
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :disabled="isDisabled"
        label-width="120px"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label="$t('internalBarcode')" prop="internalBarcode">
              <el-input
                v-model.trim="form.internalBarcode"
                :disabled="form.id?true:false"
                clearable
                style="width: 200px"
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                @change="changeToolingBarcode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('toolingBarcode')" prop="toolingBarcode">
              <el-input
                v-model.trim="form.toolingBarcode"
                :disabled="disableToolingBarcode"
                clearable
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                style="width: 200px"
                @blur="validSame"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('toolingType')" prop="toolingType">
              <el-select
                v-model.trim="form.toolingType"
                :disabled="toolingdisable"
                style="width: 200px"
                clearable
                filterable
                @change="ChangeType"
              >
                <el-option
                  v-for="item in toolingTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('toolingModel')" prop="toolingModel">
              <el-select
                v-model.trim="form.toolingModel"
                style="width: 200px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in toolingModelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('toolingImage')" prop="toolingImage">
              <template
                v-if="imageUrl || form.toolingImage"
                style="display: inline-block"
              >
                <el-button
                  type="danger"
                  style="opacity: 0.6"
                  icon="el-icon-delete"
                  circle
                  @click="ImgRemove"
                />
              </template>
              <el-upload
                ref="upload"
                :headers="headers"
                :action="updateAvatarApi"
                :show-file-list="false"
                :auto-upload="true"
                :on-success="uploadSuccess"
                :on-change="beforeUpload"
                class="upload-add"
                style="display: inline-block"
                name="uploadFile"
                accept=".PNG,.JPG,.GIF"
              >
                <template v-if="imageUrl || form.toolingImage">
                  <img
                    :src="
                      form.toolingImage
                        ? imgUrlFormatter(form.toolingImage)
                        : imageUrl
                    "
                    style="width: 100px; height: 70px; margin-left: 0px"
                  >
                </template>
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  style="margin-left: 50px"
                />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('flag')" prop="flag">
              <el-select
                v-model="form.flag"
                :disabled="toolingdisable"
                style="width: 200px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in toolingFlagList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('ToolingStatus')" prop="hdStatus">
              <el-select
                v-model="form.hdStatus"
                :disabled="toolingdisable"
                style="width: 200px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in hDStatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('stock')" prop="stock">
              <el-input
                v-model.trim="form.stock"
                clearable
                style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('owner')" prop="owner">
              <el-input v-model.trim="form.owner" clearable style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="`${$t('pmCycle')}(天)`" prop="pmCycle">
              <el-input
                v-model.trim="form.pmCycle"
                style="width: 200px"
                clearable
                onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="`${$t('lifeTime')}(次)`" prop="lifeTime">
              <el-input
                v-model.trim="form.lifeTime"
                style="width: 200px"
                clearable
                onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              />
            </el-form-item>
          </el-col>
          <el-col v-btnPermission:currentTime v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('currentTime')" prop="usedTime">
              <el-input
                v-model.trim="form.usedTime"
                style="width: 200px"
                clearable
                onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('nextPMDate')" prop="nextPMDate">
              <el-date-picker
                v-model="form.nextPMDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('handlerTypeList')" prop="handlerTypeList">
              <el-select
                v-model="form.handlerTypeList"
                style="width: 200px"
                clearable
                multiple
                filterable
              >
                <el-option
                  v-for="item in handlerTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('testerTypeList')" prop="testerTypeList">
              <el-select
                v-model="form.testerTypeList"
                style="width: 200px"
                clearable
                multiple
                filterable
              >
                <el-option
                  v-for="item in testTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col
            v-if="
              toolingTypeCategory == 1 || toolingTypeCategory == 2
            "
            :span="12"
          >
            <el-form-item :label="$t('pnNo')" prop="pnNo">
              <el-input
                v-model.trim="form.pnNo"
                clearable
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                style="width: 200px" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('ymtcNo')" prop="ymtcNo">
              <el-input
                v-model.trim="form.ymtcNo"
                clearable
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                style="width: 200px" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col
            v-if="
              toolingTypeCategory == 1 || toolingTypeCategory == 3
            "
            :span="12"
          >
            <el-form-item :label="$t('package')" prop="package">
              <el-input
                v-model.trim="form.package"
                clearable
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                style="width: 200px" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col
            v-if="
              toolingTypeCategory == 1 || toolingTypeCategory == 2
            "
            :span="12"
          >
            <el-form-item :label="$t('mfg')" prop="mfg">
              <el-input
                v-model="form.mfg"
                clearable
                onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
                style="width: 200px" />
            </el-form-item>
          </el-col> -->
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('receiveDate')" prop="receiveDate">
              <el-date-picker
                v-model="form.receiveDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('releaseDate')" prop="releaseDate">
              <el-date-picker
                v-model="form.releaseDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('siteQty')" prop="siteQty">
              <el-input
                v-model="form.siteQty"
                onkeyup="this.value = this.value.replace(/[^\d]/g,'')"
                clearable
                style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col v-if="toolingTypeCategory == 1" :span="12">
            <el-form-item :label="$t('clientBarcode')" prop="clientBarcode">
              <el-input v-model="form.clientBarcode" clearable style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('supply')" prop="Supply">
              <el-input v-model="form.supply" clearable style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('supplyModel')" prop="supplyModel">
              <el-input v-model="form.supplyModel" clearable style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('snNo')" prop="snNo">
              <el-input v-model="form.snNo" clearable style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('remark')" prop="remark">
              <el-input v-model="form.remark" type="textarea" show-word-limit maxlength="200" rows="2" style="width: 200px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!isDisabled" slot="footer">
        <el-button icon="el-icon-circle-close" @click="closeDialog">{{
          $t("cancel")
        }}</el-button>
        <el-button
          v-btnThrottle="doSave"
          type="primary"
          icon="el-icon-receiving"
        >{{ $t("save") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import crudJob from '@/api/Tooling/toolingBasicInfo'
import { getToken } from '@/utils/auth'
import mySetting from '@/mixins/mySetting'
import toolingKitApi from '@/api/Tooling/toolingKit'
// import { getEqpModelList } from '@/api/equipment/eqpbase'
export default {
  name: 'MyDialog',
  mixins: [mySetting],
  props: {
    isDisabled: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        hdStatus: 1
      },
      headers: {
        Token: getToken()
      },
      dialogFormVisible: false,
      imageUrl: '',
      disableToolingBarcode: false,
      toolingdisable: false,
      toolingTypeCategory: 0,
      toolingTypeList: [],
      toolingFlagList: [],
      toolingModelList: [],
      handlerTypeList: [],
      hDStatusList: [],
      testTypeList: [],
      fileTypeList: ['JPG', 'PNG', 'JPEG', 'GIF'], // 允许的文件上传类型,与之比较时全部转大写进行比较
      rules: {
        internalBarcode: [
          { required: true, message: this.$t('searchinternalBarcode'), trigger: 'blur' }
        ],
        toolingBarcode: [
          {
            required: true,
            message: this.$t('searchtoolingbarcode'),
            trigger: 'blur'
          }
        ],
        toolingType: [
          {
            required: true,
            message: this.$t('searchtoolingType'),
            trigger: 'change'
          }
        ],
        toolingModel: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('toolingModel')}`, trigger: 'change' }],
        stock: [
          { required: true, message: this.$t('searchstock'), trigger: 'blur' }
        ],
        flag: [
          { required: true, message: this.$t('searchflag'), trigger: 'change' }
        ],
        machineType: [
          {
            required: false,
            message: this.$t('searchmachineType'),
            trigger: 'blur'
          }
        ],
        lifeTime: [
          {
            required: false,
            message: this.$t('searchlifeTime'),
            trigger: 'blur'
          }
        ],
        pnNo: [
          { required: false, message: this.$t('searchpnNo'), trigger: 'blur' }
        ],
        ymtcNo: [
          {
            required: false,
            message: this.$t('searchymtcNo'),
            trigger: 'blur'
          }
        ],
        package: [
          {
            required: false,
            message: this.$t('searchpackage'),
            trigger: 'blur'
          }
        ],
        mfg: [
          { required: false, message: this.$t('searchmfg'), trigger: 'blur' }
        ],
        receiveDate: [
          {
            required: true,
            message: this.$t('searchreceiveDate'),
            trigger: 'change'
          }
        ],
        siteQty: [
          {
            required: false,
            message: this.$t('searchsiteQty'),
            trigger: 'blur'
          }
        ],
        clientBarcode: [
          {
            required: false,
            message: this.$t('searchclientBarcode'),
            trigger: 'blur'
          }
        ],
        owner: [
          { required: true, message: this.$t('searchowner'), trigger: 'blur' }
        ],
        hdStatus: [{ required: true, message: this.$t('searchhdStatus'), trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['user', 'updateAvatarApi', 'baseApi'])
  },
  mounted() {
    // 这什么啊...
    // this.disableFlag()
  },
  methods: {
    imgUrlFormatter(url) {
      if (url === '' || url == null || url === undefined) return
      // 当图片路径相同时,即使源图片更改了,img内显示的也不会去刷新,需要在后面加radom或者当前时间去解决
      return this.baseApi + '/' + url + '?t=' + new Date()
    },
    ChangeType() {
      crudJob.GetToolingType({ toolingType: this.form.toolingType })
        .then((res) => {
          this.toolingTypeCategory = res.data
          this.$set(this.form, 'toolingModel', '')
        })
      this.getToolingModelList(this.form.toolingType)
    },
    ImgRemove() {
      this.$refs.upload.clearFiles()
      this.imageUrl = ''
      this.form.toolingImage = ''
    },
    // 新增数据
    doSave() {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.form.id) {
          // 存在id则是更新
          crudJob.edit(this.$clearNull(this.form)).then((res) => {
            // this.doMerge(res)
            this.$betterTips(res, this.closeDialog, this.handleupdate)
          })
        } else {
          // 不存在id则是新增
          crudJob.add(this.$clearNull(this.form)).then((res) => {
            // this.doMerge(res)
            this.$betterTips(res, this.closeDialog, this.handleupdate)
          })
        }
      })
    },
    // 打开弹窗
    openDialog(row) {
      if (row && row.id) {
        crudJob.get({ id: row.id }).then((res) => {
          const flag = [2, 4, 5]
          this.form = res.data
          this.form.toolingType && this.getToolingType(this.form.toolingType) && this.getToolingModelList(this.form.toolingType)
          if (flag.includes(this.form.flag)) {
            this.toolingdisable = true
          }
          this.validSame()
        })
      } else {
        this.toolingdisable = false
        this.validSame()
      }
      this.getToolingTypeList()
      this.getToolingFlags()
      // this.getHandlerType()
      // this.getTestTypeList()
      this.getHDStatusList()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('closeDialog')
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleupdate() {
      this.$emit('initList')
    },
    uploadSuccess(file) {
      this.form.toolingImage = file.data
    },
    beforeUpload(file) {
      var isJPG = false
      for (const i in this.fileTypeList) {
        if (file.raw.type.toUpperCase().indexOf(this.fileTypeList[i]) > 0) { isJPG = true }
      }
      const isLt2M = file.raw.size / 1024 / 1024 < 5
      if (!isJPG) {
        // this.showMessage('add', 'error', '上传图片只能是 JPG/PNG/GIF 格式!')
        return false
      }
      if (!isLt2M) {
        // this.showMessage('add', 'error', '上传图片大小不能超过 2MB!')
        return false
      }
      const url = URL.createObjectURL(file.raw)
      this.imageUrl = url
      return true
    },
    changeToolingBarcode(value) {
      this.$refs['ruleForm'].clearValidate()
      this.$set(this.form, 'toolingBarcode', value)
    },
    validSame() {
      if (this.form.id) {
        if (this.form.internalBarcode !== this.form.toolingBarcode) {
          this.disableToolingBarcode = true
        } else {
          this.disableToolingBarcode = false
        }
      } else {
        this.disableToolingBarcode = true
      }
    },
    // 标志位禁用
    // disableFlag() {
    //   const flag = [2, 4, 5]
    //   return flag.includes(this.form.flag)
    // },
    async getToolingModelList(type) {
      const res = await toolingKitApi.getByTypeModelList({ toolingType: type })
      this.toolingModelList = res.data
    },
    // async getHandlerType() {
    //   const res = await getEqpModelList({ eqptype: 'HANDLER' })
    //   this.handlerTypeList = res.data
    // },
    // async getTestTypeList() {
    //   const res = await getEqpModelList({ eqptype: 'TESTER' })
    //   this.testTypeList = res.data
    // },
    // 获取完整的标识位列表
    async getToolingFlags() {
      const res = await crudJob.GetToolingFlagList()
      const allowList = [1, 3, 6, 7]
      const flags = res.data.map(item => {
        return {
          ...item,
          disabled: !allowList.includes(item.id)
        }
      })
      this.toolingFlagList = flags
    },
    // 获取残缺的标识位列表
    // async getIncompleteToolingFlagList() {
    //   const res = await crudJob.getIncompleteToolingFlagList()
    //   this.toolingFlagList = res.data
    // },
    // 获取备件类型
    async getToolingTypeList() {
      const res = await crudJob.GetToolingTypeList()
      this.toolingTypeList = res.data
    },
    // 根据toolingTypeCategory动态展示 选项字段????
    async getToolingType(type) {
      const res = await crudJob.GetToolingType({ toolingType: type })
      this.toolingTypeCategory = res.data
    },
    // 获取备件状态下拉框
    async getHDStatusList() {
      const res = await crudJob.getHDStatus()
      this.hDStatusList = res.data
    }
  }
}
</script>
